package com.ifreeee.practice.pc.bilibili;

import com.ifreeee.practice.pc.cmd.CmdUtils;
import com.ifreeee.practice.pc.map.MapUtils;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * https://www.bilibili.com/video/BV1D3411g7r6
 * you-get -c="C:\Users\Klaus\Desktop\bilibili.com_cookies.txt" -i "https://www.bilibili.com/video/BV1D3411g7r6"
 * you-get -c="C:\Users\Klaus\Desktop\bilibili.com_cookies.txt" --no-caption --format=dash-hdflv2_4k -o "F:\bilibili\wd\temp" "https://www.bilibili.com/video/BV1D3411g7r6"
 */
public class YouGetUtils {

    private static final String VEDIO_PRE = "https://www.bilibili.com/video/";

    private static final String propName = "bvid";

    private static final String sep = "\n";

    private static final String GET_INFO_CMD_PRE = "you-get -c=\"C:\\Users\\Klaus\\Desktop\\bilibili.com_cookies.txt\" -i ";

    private static final String QUOTES = "\"";

    private static final List<String> FORMAT_LIST = new ArrayList<>();

    static {
        FORMAT_LIST.add("dash-hdflv2_4k");
        FORMAT_LIST.add("dash-hdflv2");
        FORMAT_LIST.add("dash-flv");
        FORMAT_LIST.add("dash-flv720");
    }

    public static void main(String[] args) {
        List<String> allJson = GetAllJsonUtils.getAllJson();
        List<String> jsonProp = JsonPropUtils.getJsonProp(allJson, propName);
        Map<String, String> formatInfo = getFormatInfo(jsonProp);
        MapUtils.printMap(formatInfo);
        //JsonPropUtils.print(jsonProp, sep);
    }

    public static Map<String, String> getFormatInfo(List<String> jsonProp) {
        if (CollectionUtils.isEmpty(jsonProp)) {
            return null;
        }

        if (CollectionUtils.isEmpty(FORMAT_LIST)) {
            return null;
        }

        ConcurrentSkipListMap<String, String> urlToFormatInfo = new ConcurrentSkipListMap<>();
        jsonProp.parallelStream()
                .filter(Objects::nonNull)
                .map(id -> VEDIO_PRE + id)
                .forEach(vedioUrl -> {
                    String cmd = GET_INFO_CMD_PRE + QUOTES + vedioUrl + QUOTES;
                    String res = CmdUtils.runCMD(cmd);
                    if (StringUtils.isBlank(res)) {
                        return;
                    }
                    for (String format : FORMAT_LIST){
                        if(res.contains(format)) {
                            urlToFormatInfo.put(vedioUrl, format);
                            break;
                        }
                    }
                });

        return urlToFormatInfo;
    }

    @Data
    private static final class CmdParam {

        private String format;

        private boolean isMuti;




    }


}
